import Crypt from "../../../utils/Crypt";
import OrderModel from "../../../models/Order";
import UserModel from "../../../models/User";

const orderModel = new OrderModel()
const userModel = new UserModel()

Page({
  data: {
    params: {},
    productList: [],
    addressList: [],
    account: {},
    remoteCity: false,
    amount: 0,
    currentProducts: [],
    showTotal: 0,
    showPayPassword: false,
    firstProduct: {}
  },
  // 填完地址后退回来, 刷新
  onShow() {
    this.checkReferrer()
    this.checkGroup()
    this.checkSecondKill()

    this.parseParams().then(() => {
      if (Object.keys(this.data.params).length === 0) {
        // 重复提交
        return wx.switchTab({
          url: '/pages/home/index'
        })
      }

      this.getAccount().then(() => {})

      this.getAddress().then(() => {
        this.getProduct().then(() => {
          this._currentProducts()
          this._showTotal()
          this._amount()
        })
      })

    })
  },
  onLoad: function (options) {
    const params = JSON.parse(options.params)
    if (Object.keys(params).length > 0) {
      this.setData({ showButton: true })
    }
    this.setData({ params })


  },

  _currentProducts() {
    let list
    if (!this.data.params.cart) {
      list = [this.data.productList]
    } else {
      list = []
      this.data.productList.forEach(item => {
        const obj = item.product
        obj.sku = item.sku
        obj.quantity = item.quantity
        if (item.selected_sku_text) {
          obj.selected_sku_text = item.selected_sku_text
        }
        list.push(obj)
      })
    }
    this.setData({ currentProducts: list })
  },

  _showTotal() {
    const total = {
      freight: 0,
      price: 0,
      score: 0,
      platform_ticket: 0
    }
    const list = this.data.currentProducts
    let freight = 0
    let price = 0
    let score = 0
    list.forEach(x => {
      if (this.data.remoteCity) {
        freight += x.quantity * x.freight
      }
      if (x.scoreCost && x.scoreCost.total) {
        price += x.quantity * x.scoreCost.total
        if (x.sku) {
          score += x.quantity * x.sku.price
        } else {
          score += x.quantity * x.price
        }
      } else {
        if (x.sku) {
          price += x.quantity * x.sku.price
        } else {
          price += x.quantity * x.price
        }
      }
    })
    total.freight = freight.toFixed(2)
    total.price = price.toFixed(2)
    total.score = score.toFixed(2)
    this.setData({
      showTotal: total
    })
  },

  _amount() {
    let total = +this.data.showTotal.price + +this.data.showTotal.freight
    if (+this.data.account.score < +this.data.showTotal.score) {
      total += +this.data.showTotal.score - +this.data.account.score
    }
    const use = +this.data.account.platform_ticket + +this.data.account.balance
    let amount = total - use
    if (amount < 0) {
      amount = 0
    }
    const i = +Number.parseFloat(amount).toFixed(2)
    this.setData({
      amount: i
    })
  },

  checkReferrer() {
    orderModel.checkReferrer().then(response => {
      let { data } = response
      data = Crypt.parse(data)
      if (!data.result) {
        wx.showModal({
          title: '您没有推荐人，不能下单!',
          success: () => {
            // wx.navigateBack()
            wx.switchTab({
              url: '/pages/home/index'
            })
          }
        })
      }
    })
  },

  checkGroup() {
    const p = this.data.params
    if (p.group_id && +p.group_id > 0) {
      orderModel.checkGroup({ group_id: p.group_id }).then(() => {}).catch(err => {
        wx.showModal({
          title: err.message,
          success: () => {
            // wx.navigateBack()
            wx.switchTab({
              url: '/pages/home/index'
            })
          }
        })
      })
    }
  },

  checkSecondKill() {
    const p = this.data.params
    if (p.product_id && +p.product_id > 0) {
      orderModel.checkSecondKill({ product_id: p.product_id }).then(() => {}).catch(err => {
        // wx.showModal({
        //   title: err.message,
        //   success: () => {
        //     // wx.navigateBack()
        //     wx.switchTab({
        //       url: '/pages/home/index'
        //     })
        //   }
        // })
      })
    }
  },

  parseParams() {
    return new Promise(resolve => {
      const p = this.data.params
      if (Object.keys(p).length === 0) {
        const params = JSON.parse(orderModel.getParams())
        this.setData({ params })
        if (Object.keys(params).length > 0) {
          this.setData({ showButton: true })
        }
        resolve()
      } else {
        orderModel.saveParams(JSON.stringify(p))
        resolve()
      }
    })
  },

  getProduct() {
    return new Promise(resolve => {
      orderModel.getProduct({ ...this.data.params }).then(response => {
        let { data } = response
        data = Crypt.parse(data)
        this.setData({ productList: data })
        let obj
        if (Array.isArray(data) && data.length > 0) {
          obj = data[0].product
        } else {
          obj = data
        }
        this.setData({
          firstProduct: obj
        })
        resolve()
      })
    })
  },

  getAccount() {
    return new Promise(resolve => {
      orderModel.getAccount().then(response => {
        let { data } = response
        data = Crypt.parse(data)
        this.setData({ account: data })
        resolve()
      })
    })
  },

  getAddress() {
    return new Promise(resolve => {
      orderModel.getAddress().then(response => {
        let { data } = response
        data = Crypt.parse(data)
        // selected
        data.forEach((v, k) => {
          if (k === 0) {
            v.selected = true
            this.isRemoteCity(v.province_id)
          } else {
            v.selected = false
          }
        })
        this.setData({
          addressList: data
        })
        resolve()
      })
    })
  },

  isRemoteCity(province_id) {
    orderModel.isRemoteCity({province_id}).then(response => {
      let { data } = response
      data = Crypt.parse(data)
      this.setData({
        remoteCity: data.result
      })
    })
  },

  selectedAddress(e) {
    const item = e.detail.item
    const list = [...this.properties.addressList]
    list.forEach(x => {
      if (x.id === item.id) {
        x.selected = true
        this.isRemoteCity(x.province_id)
      } else {
        x.selected = false
      }
    })
    this.setData({ addressList: list })

    // 用延时解决运费bug, 后面再改
    setTimeout(() => {
      this._showTotal()
      this._amount()
    }, 200)
  },

  pay_password(e) {
    const value = e.detail.value
    this.setData({
      password: value
    })
  },

  close() {
    this.setData({
      showPayPassword: false
    })
  },

  submitPayPassword() {
    const password = this.data.password
    if (!password || password.length < 1) {
      wx.showToast({ title: '请输入支付密码', icon: 'error' })
    } else {
      userModel.verifyPayPassword({ password }).then(response => {
        const { data } = response
        const is = data.result
        if (is) {
          this._goPay()
        } else {
          wx.showToast({ title: '支付密码错误', icon: 'error' })
        }
      })
    }
  },

  goPay() {
    if (this.data.amount === 0) {
      userModel.checkPayPassword().then(response => {
        let { data } = response
        data = Crypt.parse(data)
        const is = data.result
        if (is) {
          this.setData({
            showPayPassword: true
          })
        } else {
          wx.showModal({
            title: '您还没有设置支付密码,现在去设置',
            success: res => {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/sub_service/pages/pay-password/index'
                })
              }
            }
          })
        }
      })
    } else {
      this._goPay()
    }
  },

  _goPay() {
    if (this.properties.addressList.length === 0) {
      return wx.showToast({title: '请选择收货地址'})
    }
    const address_id = this.properties.addressList.filter(x => x.selected)[0].id
    orderModel.createOrder({
      ...this.data.params,
      address_id
    }).then(response => {

      // clear
      orderModel.saveParams({})

      let { data } = response
      data = Crypt.parse(data)
      if (+data.amount === 0) {
        wx.showToast({
          title: '支付成功',
          success: () => {
            setTimeout(() => {
              if (data.is_create) {
                wx.navigateTo({
                  url: '/sub_service/pages/group/index?type=0'
                })
              } else if (data.is_join_random) {
                wx.navigateTo({
                  url: '/sub_service/pages/group/index?type=1'
                })
              } else {
                wx.navigateTo({
                  url: '/sub_service/pages/order/index?type=3'
                })

                // wx.switchTab({
                //   url: '/pages/home/index'
                // })
              }
            }, 1000)
          }
        })
      } else {
        let serial = {
          order_id: data.order_id
        }
        serial = JSON.stringify(serial)
        wx.navigateTo({
          url: '/sub_main/pages/pay/index?serial=' + serial
        })
      }
    })
  }
});
